package cn.bestick.thirteenKiller.ui;

import cn.bestick.thirteenKiller.Constants;
import cn.bestick.thirteenKiller.dao.DataBase;
import cn.bestick.thirteenKiller.dmo.CardImage;
import cn.bestick.thirteenKiller.service.impl.KillerServiceImpl;
import cn.bestick.thirteenKiller.util.PropertiesUtil;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * Created by bestick on 2016/1/17.
 */
public class JFrameKiller extends JFrame {

    private JPanelKiller panel = new JPanelKiller();
    private DataBase db = DataBase.getInstance();
    private final String COMMUNICATION = PropertiesUtil.getValue("communication");

    public JFrameKiller() {
        this.setTitle("ThirteenKiller by bestick");
        this.setResizable(false);
        this.setIconImage(Toolkit.getDefaultToolkit().getImage("resources/icon.jpg"));
        this.setBounds(500, 280, 316, 120);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
        this.panel.setList(getImgList());
        this.add(panel);
        this.initKeyListener();
    }

    private void initKeyListener() {
        addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 90) {
                    if (!JFrameKiller.this.ms()) {
                        return;
                    }
                    JFrameKiller.this.panel.setList(getImgList());
                    JFrameKiller.this.panel.north.repaint();
                    JFrameKiller.this.panel.msg.setText("秒杀成功！");
                } else if (e.getKeyCode() == 88) {
                    JFrameKiller.this.db.truncateTmp();
                    JFrameKiller.this.panel.setList(getImgList());
                    JFrameKiller.this.panel.north.repaint();
                    JFrameKiller.this.panel.msg.setText("清除完毕！");
                }
            }
        });
    }

    /**
     * 秒杀核心方法
     *
     * @return boolean
     */
    private boolean ms() {
        try {
            return new KillerServiceImpl().ms();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取图片数据
     *
     * @return List<byte[]>
     */
    private List<byte[]> getImgList() {
        if (this.COMMUNICATION.equals(Constants.COMMUNICATE_FROM_DB)) {
            return this.db.getImgData();
        } else if (this.COMMUNICATION.equals(Constants.COMMUNICATE_FROM_SOCKET)) {
            //TODO socket通信获取数据
            return null;
        }
        return null;
    }
}
